package com.lagou.edu.service.impl;

import com.lagou.edu.dao.ArticleMapper;
import com.lagou.edu.model.Article;
import com.lagou.edu.model.PageInfo;
import com.lagou.edu.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;


@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;


    @Override
    public PageInfo<Article> manualListPageArticles(Integer pageIndex, Integer pageSize) {
        List<Article> articleList = articleMapper.manualListPageArticles();
        PageInfo<Article> pageInfo = new PageInfo<>(pageIndex, pageSize);
        if (CollectionUtils.isEmpty(articleList)) {
            return pageInfo;
        }
        List<Article> subArticleList = articleList.stream().limit(pageIndex * pageSize).skip((pageIndex - 1) * pageSize).collect(Collectors.toList());
        pageInfo.setData(subArticleList);
        pageInfo.setTotal(articleList.size());
        pageInfo.setPages(articleList.size() % pageSize == 0 ? articleList.size() : (articleList.size() / pageSize + 1));
        return pageInfo;
    }

    @Override
    public PageInfo<Article> autoListPageArticles(Integer pageIndex, Integer pageSize) {
        PageInfo<Article> pageInfo = new PageInfo<>(pageIndex, pageSize);
        List<Article> articles = articleMapper.autoListPageArticles(pageInfo);
        pageInfo.setData(articles);
        pageInfo.setPages(pageInfo.getTotal() % pageSize == 0 ? pageInfo.getTotal() / pageSize : (pageInfo.getTotal() / pageSize + 1));
        return pageInfo;
    }
}
